package cn.jjxx.modules.sys.controller;

import cn.jjxx.core.common.data.DuplicateValid;
import cn.jjxx.core.config.BillConfig;
import cn.jjxx.core.model.AjaxJson;
import cn.jjxx.core.model.PageJson;
import cn.jjxx.core.model.ValidJson;
import cn.jjxx.core.query.annotation.PageableDefaults;
import cn.jjxx.core.query.data.PropertyPreFilterable;
import cn.jjxx.core.query.data.Queryable;
import cn.jjxx.core.query.utils.QueryableConvertUtils;
import cn.jjxx.core.query.wrapper.EntityWrapper;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresMethodPermissions;
import cn.jjxx.core.utils.ObjectUtils;
import cn.jjxx.core.utils.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializeFilter;
import com.beust.jcommander.internal.Lists;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import cn.jjxx.core.common.controller.BaseBeanController;
import cn.jjxx.core.security.shiro.authz.annotation.RequiresPathPermission;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import cn.jjxx.modules.sys.entity.Infc;
import cn.jjxx.modules.sys.entity.User;
import cn.jjxx.modules.sys.service.IInfcService;
import cn.jjxx.modules.sys.utils.UserUtils;

/**   
 * @Title: 接口列表
 * @Description: 接口列表
 * @author jjxx
 * @date 2018-01-13 00:29:11
 * @version V1.0   
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/sys/infc")
@RequiresPathPermission("sys:infc")
public class InfcController extends BaseBeanController<Infc> {

    @Autowired
    protected IInfcService infcService;

    public Infc get(String id) {
        if (!ObjectUtils.isNullOrEmpty(id)) {
            return infcService.selectById(id);
        } else {
            return newModel();
        }
    }

    @RequiresMethodPermissions("list")
    @RequestMapping(method = RequestMethod.GET)
    public String list(Model model, HttpServletRequest request, HttpServletResponse response) {
        return display("list");
    }

    @RequestMapping(value = "ajaxList", method = { RequestMethod.GET, RequestMethod.POST })
    @PageableDefaults(sort = "t.create_date=desc")
    private void ajaxList(Queryable queryable, PropertyPreFilterable propertyPreFilterable, HttpServletRequest request,
                          HttpServletResponse response) throws IOException {
        EntityWrapper<Infc> entityWrapper = new EntityWrapper<Infc>(entityClass);
        propertyPreFilterable.addQueryProperty("id");
        entityWrapper.setTableAlias("t.");
        entityWrapper.eq("1", 1);
        // 预处理
        QueryableConvertUtils.convertQueryValueToEntityValue(queryable, entityClass);
        SerializeFilter filter = propertyPreFilterable.constructFilter(entityClass);
        PageJson<Infc> pagejson = new PageJson<Infc>(infcService.list(queryable,entityWrapper));
        infcService.buildInfcUrl(pagejson.getResults());
        String content = JSON.toJSONString(pagejson, filter);
        StringUtils.printJson(response, content);
    }

    @RequestMapping(value = "create", method = RequestMethod.GET)
    public String create(Model model, HttpServletRequest request, HttpServletResponse response) {
        String nodeId = request.getParameter("nodeId");
        String nodeName = request.getParameter("nodeName");
        Infc infc = new Infc();
        infc.setTypeId(nodeId);
        infc.setTypeName(nodeName);
        model.addAttribute("data", infc);
        return display("edit");
    }

    @RequestMapping(value = "create", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson create(Model model, @Valid @ModelAttribute("data") Infc infc, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(infc, request, response, result);
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.GET)
    public String update(@PathVariable("id") String id, Model model, HttpServletRequest request,
                              HttpServletResponse response) {
        Infc infc = get(id);
        model.addAttribute("data", infc);
        if (StringUtils.isNoneBlank(infc.getUseEqp())) {
            model.addAttribute("useEqpList", Lists.newArrayList(infc.getUseEqp().split(",")));
        }
        return display("edit");
    }

    @RequestMapping(value = "{id}/update", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson update(Model model, @Valid @ModelAttribute("data") Infc infc, BindingResult result,
                           HttpServletRequest request, HttpServletResponse response) {
        return doSave(infc, request, response, result);
    }

    @RequestMapping(value = "/save", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson doSave(Infc infc, HttpServletRequest request, HttpServletResponse response,
                           BindingResult result) {
        AjaxJson ajaxJson = new AjaxJson();
        if (StringUtils.isNoneBlank(infc.getDefinedSql()) && !infcService.checkSql(infc.getDefinedSql())) {
            ajaxJson.fail("SQL不合法！");
            return ajaxJson;
        }
        ajaxJson.success("保存成功");
        if (hasError(infc, result)) {
            // 错误提示
            String errorMsg = errorMsg(result);
            if (!StringUtils.isEmpty(errorMsg)) {
                ajaxJson.fail(errorMsg);
            } else {
                ajaxJson.fail("保存失败");
            }
            return ajaxJson;
        }
        try {
            if (StringUtils.isEmpty(infc.getId())) {
                infcService.insert(infc);
            } else {
                infcService.insertOrUpdate(infc);
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("保存失败!<br />原因:" + e.getMessage());
        }
        return ajaxJson;
    }

    @RequestMapping(value = "{id}/delete", method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(@PathVariable("id") String id) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            infcService.deleteById(id);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "batch/delete", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public AjaxJson batchDelete(@RequestParam(value = "ids", required = false) String[] ids) {
        AjaxJson ajaxJson = new AjaxJson();
        ajaxJson.success("删除成功");
        try {
            List<String> idList = java.util.Arrays.asList(ids);
            infcService.deleteBatchIds(idList);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxJson.fail("删除失败");
        }
        return ajaxJson;
    }

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    public String view(Model model, @PathVariable("id") String id, HttpServletRequest request,
                       HttpServletResponse response) {
        Infc infc = get(id);
        model.addAttribute("data", infc);
        return display("edit");
    }

    @RequestMapping(value = "validate", method = { RequestMethod.GET, RequestMethod.POST })
    @ResponseBody
    public ValidJson validate(DuplicateValid duplicateValid, HttpServletRequest request) {
        ValidJson validJson = new ValidJson();
        Boolean valid = Boolean.FALSE;
        try {
            EntityWrapper<Infc> entityWrapper = new EntityWrapper<Infc>(entityClass);
            valid = infcService.doValid(duplicateValid,entityWrapper);
            if (valid) {
                validJson.setStatus("y");
                validJson.setInfo("验证通过!");
            } else {
                validJson.setStatus("n");
                if (!StringUtils.isEmpty(duplicateValid.getErrorMsg())) {
                    validJson.setInfo(duplicateValid.getErrorMsg());
                } else {
                    validJson.setInfo("当前信息重复!");
                }
            }
        } catch (Exception e) {
            validJson.setStatus("n");
            validJson.setInfo("验证异常，请检查字段是否正确!");
        }
        return validJson;
    }

    @ResponseBody
    @RequestMapping(value = "enabled")
    public AjaxJson batchEnabled(HttpServletRequest request,String[] ids){
        AjaxJson j = new AjaxJson();
        j.setMsg("批量启用成功");
        List<String> bills = Arrays.asList(ids);
        try {
            List<Infc> entityList = setBacthUpdate(bills, String.valueOf(BillConfig.ENABLED));
            infcService.updateBatch(entityList);
        } catch (Exception e) {
            j.setMsg("批量启用失败,数据已被其他单据使用");
            e.printStackTrace();
        }
        return j;
    }

    /**
     * @Description: 批量禁用核数据.<br>
     * @param request http请求.<br>
     * @param ids 传入的id集合.<br>
     * @return AjaxJson 处理结果.<br>
     * @author ml .<br>
     * @date 2022-01-25 09:26:29 .<br>
     */
    @ResponseBody
    @RequestMapping(value = "unabled")
    public AjaxJson batchDisabled(HttpServletRequest request,String[] ids){
        AjaxJson j = new AjaxJson();
        j.setMsg("批量禁用成功");
        List<String> bills = Arrays.asList(ids);
        try {
            List<Infc> entityList = setBacthUpdate(bills, String.valueOf(BillConfig.DISABLED));
            infcService.updateBatch(entityList);
        } catch (Exception e) {
            j.setMsg("批量禁用失败,数据已被其他单据使用");
            e.printStackTrace();
        }
        return j;
    }

    private List<Infc> setBacthUpdate(List<String> bills,String newStatus){
        List<Infc> list = new ArrayList<Infc>();
        User user = UserUtils.getUser();
        if(bills.size()>0){
            list = infcService.selectBatchIds(bills);
            for(Infc bean:list){
                bean.setStatus(Integer.valueOf(newStatus));
                if(newStatus.equals(String.valueOf(BillConfig.SAVE))||
                        newStatus.equals(String.valueOf(BillConfig.SUBMIT))){
                }
            }
        }
        return list;
    }

    /**
     * 根据code获取接口数据
     * @param request 接口编号
     * @return json
     */
    @RequestMapping(value = "getnetdata")
    @ResponseBody
    public void infcData(HttpServletRequest request,HttpServletResponse response) {
    	try {
    		AjaxJson result = infcService.infcData(request);
        	String content = JSON.toJSONString(result.getData());
            StringUtils.printJson(response, content);
    	}
    	catch(Exception ex) 
    	{
    		AjaxJson result = new AjaxJson();
    		result.setRet(-1);
    		result.fail("查询失败");
    		String content = JSON.toJSONString(result);
            StringUtils.printJson(response, content);
    	} 
    }

    @RequestMapping(value = "getById")
    @ResponseBody
    public AjaxJson getById(String id) {
        AjaxJson result = new AjaxJson();

        result.setData(get(id));

        return result;
    }
}
